<template>
	<div style="--menu-height:200px;width: inherit;height: inherit;" @click="showt" @dblclick="closedrop" v-click-outside="onClickoutside" ref='dmselect' @keyup="selectrow" >		
		<el-input v-model="inputval" ref="dmselect" :readonly="readonly" :disabled="disabled" :clearable="clearable" @focus = "focus" @blur="blur" @change="change" @input="input"></el-input>
		<div v-if="showtable" class="tablediv" :style="'margin-top:'+margintop+'px;'" :class="{'drop-menu-open':show,'drop-menu-close':!show}">			
			<div class="head">
				<div v-for="(col,index) in tcolumns" :style="'width:'+col.width+'px;'">{{col.label}}</div>
			</div>
			<div class="content"  @keyup="selectrow" ref="content" @dblclick.stop="dbselectrow" @scroll="scrollEvent">
				<div class="row" v-for="(item,index) in info" :class="{'activerow':rowIndex == index}" @click="setCurrent($event,index)">
					<template v-for="(col,cindex) in tcolumns">
						<div v-if="col.keyVal" class="tdcell" :style="'width:'+col.width+'px;'">{{keyVal(col.keyVal,item[col.prop])}}</div>
						<div v-else class="tdcell" :style="'width:'+col.width+'px;'">{{item[col.prop]}}</div>
					</template>
					
				</div>
			</div>
			
		</div>
	</div>
</template>

<script>
//	@click.stop : 阻止事件冒泡
//	@click.prevent : 阻止事件默认行为
//	@click.self : 事件只作用在元素本身，而不是其子元素
	import clickOutside from "@/directives/clickoutside.js"
	import {wpgetDataByPage} from '@/system/api/cellView'
	import { encrypt } from '@/utils/jsencrypt'
	export default {
	name: "dmSelect",
	directives: { clickOutside },
	components:{		
	},
	model: {
    	prop: 'val',
    	event: 'input'
  	},
	props:{
		val:{default:null},//值
        columns:{default:null},//[{"prop":"name","label":"姓名","width":100},{"prop":"code","label":"编码","width":150},{"prop":"flag","label":"是否admin","width":100,"format":[{"0":"否"},{"1":"是"}]}]
        sql:{default:null},//sql语句，根据val 向后台查询数据 where name like '%w%' or hwpy(name) like '%w%'  select id,name,flag,code,dept_id,account from t_user      
        readonly:{default:null},//返回  {"tbindex":0,"record":{"qt":"name"}}
        disabled:{default:false},
        clearable:{default:true},
	},
	watch:{
      // 反向选择：监听value，当value因外界修改发生改变时选中自动选中option
      val: function(newValue){       	
		  this.inputval = newValue;
		  console.log(newValue)
      	if(this.inputval==null || this.inputval ==""){
    		this.info = [];
    	}
      }
    },
    computed: {
    	keyVal:function(){
			return function(arr,val){				
				let rs = null;
				for(let i=0;i<arr.length;i++){
					let obj = arr[i];
					for(let key in obj){
						if(key.toString()==val.toString()){
							rs = obj[key];
						}
					}
				}
				return rs;
			}
		},
    },
    data() {
      return {       	
      	inputval:null,
      	tableHeight:210,
      	showtable:false,
      	show:true,
      	info:[],
      	rowIndex:0,
      	tcolumns:[],
      	tblwidth:0,
      	margintop:0,
      	start:0,
      	limit:20,
      	totalCount:99999,
      	dbclick:false,
      };
    },
    mounted(){      	
    	this.inputval = this.val;
    	if(this.inputval==null || this.inputval ==""){
    		this.info = [];
    	}
    	this.tblwidth = 30;//content  左边距 右边距 加起来 是30px
    	if(this.columns){    		
    		this.tcolumns = JSON.parse(this.columns);
    		for(let i=0;i<this.tcolumns.length;i++){ 
    			let col = this.tcolumns[i];
    			this.tblwidth = this.tblwidth + col.width;
    		}
    	}
    	this.$refs.dmselect.style.setProperty('--menu-height', this.tableHeight+'px');
    },
    methods: { //this.$emit("setSelect",v)
    	wpgetDataByPage(){//查询sql 
    		if(this.inputval !=null && this.inputval !="" && this.sql){//输入条件为空不查询    	
    			if(this.info.length < this.totalCount){//如果数据到了最大的数值，就不再查询
    				let sql = this.$parent.$parent.userEvents.fieldReplace(this.sql);  
//  				console.log(sql);
		    		sql = encodeURIComponent(sql.trim())	    		
					let sqlArr = []			
					let n = 100
					for(let i = 0, l = sql.length; i < l / n; i++) {
						let a = sql.slice(n * i, n * (i + 1))
						sqlArr.push(encrypt(a))
					}
					let param = {sql:sqlArr,start:this.start,limit:this.limit}
					wpgetDataByPage(param).then((res) => {
						if(res.success){
							for(let i=0;i<res.info.length;i++){
								let rs = res.info[i];
								let obj = {};
								for(let key in rs){
									this.$set(obj,key.toLowerCase(),rs[key]);
									// console.log(obj)
								}
								
								this.info.push(obj);
							}
							this.totalCount = res.totalCount;
						}
					})
    			}
    			
}    		
    	},
    	showt(){  
    		this.dbclick = false;
    		let evt = event;
    		if(event.target.className =='el-input__inner' && !this.disabled){
    			setTimeout(()=>{  				
	    			if(!this.dbclick){      			
		    			let clientHeight = document.documentElement.clientHeight;
			    		let cellHeight = evt.clientY;
			    		this.margintop = 0;
			    		if(this.tableHeight + cellHeight + 2 > clientHeight){
			    			this.margintop = -this.tableHeight - this.$refs.dmselect.clientHeight - 2;
			    		}else{
			    			this.margintop = 1;
			    		}
			    		this.start = 0;  
		    			this.info = [];
		    			this.totalCount=99999;
		    			this.rowIndex = 0;
			    		this.wpgetDataByPage();
			    		this.showtable = true;	  
			    		this.show = true;
		    		}
	    		},200);
    		}
    		    		
    		//console.log(this.$parent.$parent.userEvents.fieldReplace(xxx))
    	},
    	closedrop(){
    		this.showtable = false;	
    		this.show = false;
    		this.dbclick = true;    		
    	},
    	onClickoutside(){    		
			if(this.showtable == true){
				this.show = false;
				setTimeout(()=>{ 
					this.showtable = false;		
				},300);
			}				
		},
		dbselectrow(){
			if(this.showtable){	
				this.show = false;
				setTimeout(()=>{ 
					this.showtable = false;		
				},300);
				this.$emit("setSelect",this.info[this.rowIndex])					
				this.$refs.dmselect.children[0].children[0].blur();				
			}
		},
		selectrow(e){			
			if(this.showtable){
				if(e.key == "ArrowDown"){
					if(this.rowIndex < this.info.length -1){
						this.rowIndex = this.rowIndex + 1	
						if(this.rowIndex>2){
							this.$refs.content.scrollTop = this.$refs.content.scrollTop + 40;
						}
						
					}				
					
				}
				if(e.key == "ArrowUp"){
					if(this.rowIndex > 0){
						this.rowIndex = this.rowIndex - 1	
						if(this.rowIndex>1){
							this.$refs.content.scrollTop = this.$refs.content.scrollTop - 40;
						}						
					}
				}
				if(e.key == "Enter"){
					this.show = false;
					setTimeout(()=>{ 
						this.showtable = false;		
					},300);
					this.$emit("setSelect",this.info[this.rowIndex])					
					this.$refs.dmselect.children[0].children[0].blur();
				}
			}
			
		},
    	selectRow(e){
    		console.log(e);
    	},
    	setCurrent(e,index) {
        	this.rowIndex = index;       	
      	},    	
    	blur(e){ 
    		this.$emit('blur',e); 
    	},
    	focus(e){
    		this.$emit('focus',e);
    	},
    	change(e){
    		this.$emit('change',e);  
    	},
    	input(e){//输入框内容变更
    		this.$emit('input',e);  
    		this.start = 0;  
    		this.info = [];
    		this.totalCount=99999;
    		this.rowIndex = 0;
    		this.wpgetDataByPage();
    	},    
    	scrollEvent(e){//滚动条到底事件
    		if (e.srcElement.scrollTop + e.srcElement.clientHeight == e.srcElement.scrollHeight ) {    			
    			this.start = this.start + 1;
    			this.wpgetDataByPage();		        
		    }
    	}
    }
  }
</script>

<style scoped>
	/*element 输入框样式*/
	>>>.el-input {
		height: 100%;
	}

	>>>.el-input__inner {
		height: 100%;
		border: none;
		border-radius: 0px;
		color: var(--input-text-color);
		font-size: 14px;
		font-family: Microsoft YaHei;
		font-weight: 400;
		text-align: inherit;
	}
	/*element 输入框的 focus hover样式*/
	>>>.el-input__inner:focus,
	>>>.el-textarea__inner:focus {
		background: var(--input-focus-back-color);
	}
	>>>.el-input__inner:hover,
	>>>.el-textarea__inner:hover {
		background: var(--input-hover-back-color);
	}
	
	.tablediv{
		position: fixed;
		z-index: 99;
		background: var(--business-page-content-bgc);
		box-shadow:0px 10px 20px 0px var(--drop-menu-boxshadow-color), 0px -10px 20px 0px var(--drop-menu-boxshadow-color);
		border-radius: 4px;	
		padding-bottom: 10px;
	}
	.head{
		display: flex;
		padding: 0 10px 0 30px;
		height: 40px;
		line-height: 40px;
    	background-color: var(--business-table-header-bgc);
    	font-size: 12px;
    	font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
    	font-weight: bold;
    	color: var(--business-table-header-text-color);
	}
	.content{
		height: 160px;
		overflow-y: auto;
	}
	.row{
		display: flex;
		padding: 0 10px 0 30px;
		height: 40px;
    	background-color: var(--business-page-content-bgc);
    	box-shadow: 0px 1px 0px 0px var(--business-table-row-boxshadow);
    	font-size: 12px;
    	font-family: MicrosoftYaHei;
    	color: var(--business-table-text-color);
    	line-height: 40px;
	}	
	.tdcell{
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.row:nth-child(even){
		background: var(--table-row-odd-back-color);
	}
	.row:nth-child(odd){
		background: var(--table-row-even-back-color);
	}
	.row:hover{
		background: var(--table-row-hover-color);
	}
	.content .activerow{
		background: var(--table-row-hover-color);
	}
	
	.drop-menu-open{
		height: auto;
		animation: menuopen 0.3s;
	}
	@keyframes menuopen {
		from {			
			height: 0;
		}
		to {			
			height: var(--menu-height);
		}
	}
	.drop-menu-close{
		height: 0;
		animation: menuclose 0.3s;
	}
	@keyframes menuclose{
		from{
			height: var(--menu-height);
		}
		to{
			height: 0;
		}
	}
</style>